package com.example.recall_application.mvp.incomingcall;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;

import androidx.annotation.RequiresApi;
import android.telecom.TelecomManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.internal.telephony.ITelephony;
import com.example.recall_application.app.Constants;
import com.example.recall_application.mvp.entity.EventBusPhone;
import com.example.recall_application.mvp.entity.EventBusPhoneErrorLog;
import com.example.recall_application.mvp.entity.EventBusPhonePRMN;
import com.example.recall_application.mvp.presenter.ContacksPresenter;
import com.example.recall_application.mvp.presenter.MainPresenter;
import com.example.recall_application.mvp.ui.activity.MainActivity;
import com.example.recall_application.utils.PhoneUtil;

import org.simple.eventbus.EventBus;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PhoneListener extends BroadcastReceiver {
    boolean flag = false;
    static ArrayList<String> cach = new ArrayList<>();
    public static boolean flag_all = false;//挂断开关
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.e("PhoneListener",action);
        if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
        } else {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Service.TELEPHONY_SERVICE);
            String incoming_number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            switch (tm.getCallState()) {
                case TelephonyManager.CALL_STATE_RINGING:
//                    incoming_number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
//                    try {
//                        //3s后再开启activity，是为了挡在系统的接听界面之前
//                        Thread.sleep(3000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    Intent tmpI = new Intent(context, IncomingCallActivity.class);
//                    tmpI.putExtra(IncomingCallActivity.INCOMING_CALL_NAME,incoming_number);
//                    tmpI.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    context.startActivity(tmpI);
                    rejectCall(context,incoming_number);

                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:

                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                     handlePRMN(context,incoming_number);
                      handleIdle(context,incoming_number);
                    break;
            }
        }
    }

    private void handlePRMN(Context context, String phone) {
        List<String> resultList= new ArrayList<>(Arrays.asList(MainPresenter.config_p.getPRMN().split(",")));
        if(phone!=null&& resultList.contains(phone)){

            new Handler().postDelayed(new Runnable(){

                public void run() {

                    //execute the task
                    EventBusPhonePRMN eventBusPhone = new EventBusPhonePRMN();
                    eventBusPhone.setPhone(phone);
                    EventBus.getDefault().post(eventBusPhone);
                }

            }, 2000);


        }
    }

    /**
     * 如发生非应用主动挂断电话的情况，即监听到有挂断记录，但不是应用主动拦截，通过非主动挂断接口上报相关信息
     * @param context
     * @param phone
     * 挂断后注册sip模块
     */
    private void handleIdle(Context context, String phone) {
        if(phone!=null&& cach.contains(PhoneUtil.handlePhone(phone))){
            //暂时不上报了
           // IdleCall(phone);

//            handleErrorLog(phone);
//           handlePRMN(context,phone);


        }else if(phone == null){
            cach.clear();
            cach.addAll(MainPresenter.mData);
        }
    }

    private void IdleCall(String phone) {
        EventBusPhone eventBusPhone = new EventBusPhone();
        eventBusPhone.setPhone(phone);
        EventBus.getDefault().post(eventBusPhone);
    }

    @TargetApi(Build.VERSION_CODES.P)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("MissingPermission")
    public void rejectCall(Context context,String phone) {
        try {
            if(phone!=null&& !MainPresenter.mData.contains(PhoneUtil.handlePhone(phone)) && flag_all){
                try {
                    Method method = Class.forName("android.os.ServiceManager")
                            .getMethod("getService", String.class);
                    IBinder binder = (IBinder) method.invoke(null, new Object[]{Context.TELEPHONY_SERVICE});
                    ITelephony telephony = ITelephony.Stub.asInterface(binder);
                    if(isHightVersion()){
                        if (MainActivity.sip_flg == 1) {
                            EventBus.getDefault().post(Constants.Sip_register);
                        }
                        ((TelecomManager) context.getSystemService(context.TELECOM_SERVICE)).endCall();
                    }else{
                        if (MainActivity.sip_flg == 1) {
                            EventBus.getDefault().post(Constants.Sip_register);
                        }
                        telephony.endCall();
                    }

                } catch (Exception e) {
                    Log.d("", "rejectCall: ");
                    //((TelecomManager) context.getSystemService(context.TELECOM_SERVICE)).endCall();
                    handleErrorLog(phone);
                }

            }
//            ((TelecomManager) context.getSystemService(context.TELECOM_SERVICE)).endCall();

        }catch (Exception e){
            e.printStackTrace();
            Log.d("","Exception here hangUp2");
            handleErrorLog(phone);
        }finally {

        }
    }

    private void handleErrorLog(String phone) {
        EventBusPhoneErrorLog eventBusPhone = new EventBusPhoneErrorLog();
        eventBusPhone.setPhone(phone);
        EventBus.getDefault().post(eventBusPhone);
    }

    public boolean isHightVersion(){
        int version = Build.VERSION.SDK_INT;
        if (version >= 28){
            return true;
        }
        return false;
    }

}